package com.market.manage.service.impl;

import com.market.manage.mapper.ArticleMapper;
import com.market.manage.mapper.AttRecMapper;
import com.market.manage.mapper.RoleMapper;
import com.market.manage.mapper.UsersMapper;
import com.market.manage.po.Article;
import com.market.manage.po.AttRec;
import com.market.manage.po.Users;
import com.market.manage.service.MailService;
import com.market.manage.service.UsersService;
import com.market.po.Result;
import com.market.utils.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {
    @Value("${imgHost}")
    private String imgHost;
    @Resource
    private AttRecMapper attRecMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private MailService mailServiceImpl;
    SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
    SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void piZhun(String id) throws MessagingException {
        Article article = articleMapper.getById(Long.parseLong(id));
        String userId = article.getStatus();
        String mail = usersMapper.selById(Long.parseLong(userId));
        mailServiceImpl.sendHtmlMail(usersMapper.selById(Long.parseLong(userId)), "考勤管理", "您的请假已经批准");
        int i = attRecMapper.piZhun(Long.parseLong(userId));
        System.out.println(i);
    }

    /**
     * 请假
     *
     * @param time
     * @param reason
     */
    @Override
    public void leave(String id, String name, String[] time, String reason) throws ParseException {
        Article article = new Article();
        Date t0 = utcFormat.parse(time[0].replace("Z", " UTC"));
        Date t1 = utcFormat.parse(time[1].replace("Z", " UTC"));
        article.setTitle("员工请假通知");
        String sb = "请假人：" +
                name +
                "<br>" +
                "请假时间：" +
                defaultFormat.format(t0) +
                "到" +
                defaultFormat.format(t1) +
                "<br>" +
                "请假原因：" +
                reason;
        article.setContent(sb);
        article.setCreated(new Timestamp(System.currentTimeMillis()));
        List<Users> users = usersMapper.selAll();
        StringBuilder sbf = new StringBuilder();
        for (Users u : users) {
            if ("3".equals(u.getRid() + "")) {
                sbf.append(u.getId());
                sbf.append(",");
            }
        }
        if (sbf.length() > 0) {
            sbf.deleteCharAt(sbf.length() - 1);
        }
        article.setStatus(id);
        article.setUserId(sbf.toString());
        articleMapper.insArticle(article);
        //获取两个日期之间间隔的天数
        int distanceOfTwoDate = (int) DateUtil.getDistanceOfTwoDate(t0, t1);
        AttRec attRec = null;
        for (int i = 0; i < distanceOfTwoDate; i++) {
            attRec = new AttRec();
            attRec.setUserid(Long.parseLong(id));
            attRec.setStatus("3");
            Calendar c = Calendar.getInstance();
            c.setTime(t0);
            c.add(Calendar.DAY_OF_MONTH, i);
            //请假区间
            attRec.setAttTime(c.getTime());
            attRecMapper.insert(attRec);
        }

    }

    /**
     * 登录
     *
     * @param users
     * @return
     */
    @Override
    public Result login(Users users) {
        Result result = new Result();
        users.setPassword(MD5Utils.md5(users.getPassword()));
        Users user = usersMapper.selUser(users);
        if (user != null) {
            user.setJob(roleMapper.selByRid(user.getRid()));
            user.setPassword("");
            result.setItems(user);
        } else {
            result.setStatus("0");
        }
        return result;
    }

    /**
     * 获取用户列表
     *
     * @param role
     * @param name
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public Result getUsers(String role, String name, Long pageIndex, Long pageSize) {
        Result result = new Result();
        pageIndex = (pageIndex - 1) * pageSize;
        List<Users> users = usersMapper.selUsers(role, name, pageIndex, pageSize);
        result.setMessage(users);
        result.setTotal(usersMapper.countUsers());
        return result;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result delete(Long id) {
        Result result = new Result();
        int delete = usersMapper.delete(id);
        if (delete <= 0) {
            result.setStatus("0");
        }
        return result;
    }

    /**
     * 获取全部用户信息
     *
     * @return
     */
    @Override
    public Result getAllUsers() {
        List<Users> allUsers = usersMapper.getAllUsers();
        Result result = new Result();
        result.setMessage(allUsers);
        return result;
    }

    /**
     * 编辑用户信息
     *
     * @param base64
     * @param user
     */
    @Override
    public void edit(String base64, Users user) {
        if (!StringUtils.isEmpty(base64)) {
            //base64转file
            MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(base64);
            assert file != null;
            String fileName = FileUtil.getFileName(file);
            String location = "D:\\images\\thumbs";
            String path = location + File.separator + fileName;
            String url = "";
            // 查看路径是否存在，不存在就创建
            if (!new File(location).exists()) {
                boolean mkdirs = new File(location).mkdirs();
            }
            try {
                file.transferTo(new File(path));
                url = imgHost + "\\thumbs\\" + fileName;
                user.setThumb(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        usersMapper.updUser(user);
    }

    /**
     * 添加用户信息
     *
     * @param user
     */
    @Override
    public void add(MultipartFile file, Users user) {
        user.setPassword(MD5Utils.md5(user.getPassword()));
        user.setId(IDUtils.genItemId());
        user.setThumb(uploadThumb(file));
        user.setDate(new Timestamp(System.currentTimeMillis()));
        usersMapper.addUser(user);
    }

    @Override
    public Long countUsers() {
        return usersMapper.countUsers();
    }

    @Override
    public Long check(Long userId) {
        return usersMapper.check(userId);
    }

    @Override
    public void pass(String username, String pass) {
        String password = MD5Utils.md5(pass);
        usersMapper.updaPass(username, password);
    }

    @Override
    public Users getUser(String username) {
        return usersMapper.getUserByUsername(username);
    }


    private String uploadThumb(MultipartFile file) {
        String fileName = FileUtil.getFileName(file);
        String location = "D:\\images\\thumbs";
        String path = location + File.separator + fileName;
        String url = "";
        // 查看路径是否存在，不存在就创建
        if (!new File(location).exists()) {
            boolean mkdirs = new File(location).mkdirs();
        }
        try {
            file.transferTo(new File(path));
            url = imgHost + File.separator + "thumbs" + File.separator + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }
}
